interface dateInfoI {
  yyyy: number | string,
  MM: number | string,
  dd: number | string,
  HH: number | string,
  mm: number | string,
  ss: number | string,
  ms: number | string,
}

// 参数统一化
const _formatNormalize = (formatter: any) => {
  if (typeof formatter === 'function') {
    return formatter
  } else if (typeof formatter !== 'string') {
    throw new TypeError('参数错误，应为string|func')
  }

  if (formatter === 'data') {
    formatter = 'yyyy-MM-dd'
  } else if (formatter === 'datatime') {
    formatter = 'yyyy-MM-dd HH:mm:ss'
  }

  const formatterFunc = (dateInfo: dateInfoI) => {
    const { yyyy, MM, dd, HH, mm, ss, ms } = dateInfo

    return formatter
      .replaceAll('yyyy', yyyy)
      .replaceAll('MM', MM)
      .replaceAll('dd', dd)
      .replaceAll('HH', HH)
      .replaceAll('mm', mm)
      .replaceAll('ss', ss)
      .replaceAll('ms', ms)
  }

  return formatterFunc
}

// 补0函数
const _pad = (dateInfo: any, prop: any, len: number): string => {
  dateInfo[prop] = dateInfo[prop].padStart(len, '0')
  return dateInfo[prop]
}

const formate = (date: Date, formatter: any, isPad: boolean = false) => {
  formatter = _formatNormalize(formatter)

  const dateInfo: dateInfoI = {
    yyyy: date.getFullYear().toString(),
    MM: (date.getMonth() + 1).toString(),
    dd: date.getDate().toString(),

    HH: date.getHours().toString(),
    mm: date.getMinutes().toString(),
    ss: date.getSeconds().toString(),
    ms: date.getMilliseconds().toString()
  }

  if (isPad) {
    dateInfo.yyyy = _pad(dateInfo, 'yyyy', 4)
    dateInfo.MM = _pad(dateInfo, 'MM', 2)
    dateInfo.dd = _pad(dateInfo, 'dd', 2)
    dateInfo.HH = _pad(dateInfo, 'HH', 2)
    dateInfo.mm = _pad(dateInfo, 'mm', 2)
    dateInfo.ss = _pad(dateInfo, 'ss', 2)
    dateInfo.ms = _pad(dateInfo, 'ms', 3)
  }

  const res = formatter(dateInfo)
  console.log(res)

  return res
}

export {
  formate
}